package com.yanxu.nio.c2;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author 折戟沉沙铁未销
 * @Description: 黏包半包问题处理
 */
@Slf4j
public class ByteBufferSplitPackage {
    public static void main(String[] args) {
//        ByteBuffer temp = ByteBuffer.allocate(1024);
//        temp.put("hello,world".getBytes(Charset.defaultCharset()));
//        temp.flip();
//        System.out.println(Charset.defaultCharset().decode(temp).toString());



        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI am zhangsan\nHo".getBytes(Charset.defaultCharset()));
        splitAndRead(source);
        source.put("w are you?\n".getBytes(Charset.defaultCharset()));
        splitAndRead(source);
    }

    private static void splitAndRead(ByteBuffer source) {
        //翻转，切换到读模式
        source.flip();
        int limit = source.limit();
        for (int i = 0; i < limit; i++) {
            if (source.get(i) == '\n') {  //读取到 \n 说明，已经读取到了一个完整的消息
                int capacity = i + 1 - source.position();
                ByteBuffer tempByteBuffer = ByteBuffer.allocate(capacity);
                for (int j = 0; j < capacity; j++) {
                    tempByteBuffer.put(source.get());
                }
                tempByteBuffer.flip();
                String s = Charset.defaultCharset().decode(tempByteBuffer).toString();
                log.info("消息为: {}", s);
            }
        }
        source.compact();
    }
}